//
//  VCReceipt.m
//  express
//
//  Created by mac1 on 15/9/14.
//  Copyright (c) 2015年 longchen. All rights reserved.
//

#import "VCReceipt.h"
#import "FMDB.h"
#import "ModOrder.h"
#import "MyFMDB.h"

@interface VCReceipt ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate>

//背景图像
@property (nonatomic, strong) UIImageView* backImageView;

//声明一个数据库对象
@property (nonatomic, strong) FMDatabase * dataBase;

//图片二进制数据
@property (nonatomic, strong) NSData* dataImage;

//订单
@property (nonatomic, strong) ModOrder* order2;

@end

@implementation VCReceipt

- (void)viewDidLoad
{
    [super viewDidLoad];
    
   self.view.backgroundColor = [UIColor orangeColor];
    
    //显示图像
    self.backImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    
    [self.view addSubview:self.backImageView];
    
    //初始化定单
    self.order2 = [[ModOrder alloc]init];
    
    DBManager * dbManager = [[DBManager alloc]init];
    
    NSLog ( @" %@ ", [dbManager openDatabase:@"data2.sqlite"]);
    
    NSLog ( @" %@ ", [dbManager createTable:@"create table if not exists order2(serial integer primary key autoincrement, orderno varchar(32))"]);

    [dbManager.dataBase executeUpdate:@"insert into order2(orderno) values('ddd')"];

    NSLog ( @" %@ ", NSHomeDirectory());

//    //打开数据库,如果没有,则创建一个
//    [self openDatabase];

    //打开或创建数据表
//    [self createTable];

//    //创建一个订单记录
//    [self tableInsert];

//    //查讯定单, 将数据从数据库读取出来
//    [self tableSelected];

    //如果数据库中己经存在图片数据，则直接显示，否则弹窗拍照
    //NSLog ( @" 图片路径为%@ ", self.order2.strPhoto );

    if(self.order2.strPhoto == nil)
    {
        //弹出对话框，点击确定后开始拍照/打开图片库选取图片
        [self showAlert];
    }
    else
    {
        NSString * strPath = [[NSBundle mainBundle]pathForResource:self.order2.nSerial.stringValue ofType:@"jpg"];
        
        self.backImageView.image = [UIImage imageWithContentsOfFile:strPath];
    }
    
    //关闭数据库
    [self.dataBase close];
//    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 弹出拍照提示框
-(void)showAlert
{
    UIAlertView *altertView = [[ UIAlertView alloc ] init ];
    
    altertView. alertViewStyle = UIAlertViewStyleDefault;
    
    altertView. message = @" 您还没有拍照 ，是否拍照留底 " ;
    
    altertView. delegate = self ;
    
    //为alertView添加按钮
    [altertView addButtonWithTitle : @" 取消 " ];
    
    [altertView addButtonWithTitle : @" 确定 " ];
    
    [altertView show ];
}

-( void )alertView:( UIAlertView *)alertView clickedButtonAtIndex:( NSInteger )buttonIndex
{
    //如果选择了确定按钮
    if(buttonIndex == 1)
    {
        //选择一张照片
        [self selectPhoto];
    }
}

-(void)selectPhoto
{
    //相册是可以用模拟器打开的
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        
        picker.delegate = self;
        
        //是否可以编辑
        picker.allowsEditing = YES;
        
        //打开相册选择照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        
        [alert show];
    }
}

//!@brief 选择照片完成后回调
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //将图片显示出来
    self.backImageView.image = image;
    
    //一次缩放
    UIImage* imageNew = [self scaleImage:image toScale:0.5];
    
    //二次压缩
    self.dataImage = UIImageJPEGRepresentation(imageNew, 0.001);
    
    //存储到沙盒的路径
    NSString *path = [NSString stringWithFormat:@"%@/Documents/%@.jpg", NSHomeDirectory(), self.order2.nSerial.stringValue];

    [self.dataImage writeToFile:path atomically:YES];
    
    //NSLog ( @" 图片将要写入的路径为%@ ", path );
    
    //路径保存到数据库
    BOOL bUpdate = [self.dataBase executeUpdate:@"update order2 set photo = ? where serial = ?", path, self.order2.nSerial];
    NSLog ( @" bUpdate = %d ", bUpdate );
    
    //图片存入相册
    //UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//拍照界面点击cancel时的回调
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 对图片进行缩放
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    
    return scaledImage;
}

#pragma mark - 数据库操作
//打开数据库
-(void)openDatabase
{
    //设置 数据库的路径
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/data.sqlite" , NSHomeDirectory ()];
    
    //NSLog(@"filePath路径为%@", filePath);
    
    NSFileManager * fileManager = [[NSFileManager alloc]init];

    //如果数据库文件不存在，就创建一个
    if(![fileManager fileExistsAtPath:filePath])
    {
        //数据库文件不存在，创建一个
        BOOL createSqlite =  [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        
        NSLog ( @"数据库不存在，将创建一个createSqlite = %d ", createSqlite );
    }
    
    //如果没有数据库, 则创建一个然后打开 ; 如果有, 则直接打开
    self.dataBase = [[FMDatabase alloc]initWithPath:filePath];
    
    //如果打开失败,则提示失败
    if (!self.dataBase.open )
    {
        NSLog (@"打开数据库失败 ");
    }
}

//数据查讯
-( void )tableSelected
{
    NSString *sql = @"select * from order2" ;

    //使用 excuteQuery 查询表单
    FMResultSet *result = [self.dataBase executeQuery:sql];

    //NSLog ( @" result%@ ", result );
    
    // 执行查询语句
    while ([result next])
    {
        self.order2.nSerial = [NSNumber numberWithInt:[result intForColumn:@"serial"]];
        
        self.order2.strOrderNo = [result stringForColumn:@"orderno"];
        
        self.order2.strCompany = [result stringForColumn:@"company"];
        
        self.order2.strStatus = [result stringForColumn:@"status"];
        
        self.order2.strUpdateTime = [result stringForColumn:@"updatetime"];
        
        self.order2.strRemark = [result stringForColumn:@"remark"];
        
        self.order2.strGoods = [result stringForColumn:@"goods"];
        
        self.order2.strFrom = [result stringForColumn:@"from2"];
        
        self.order2.strTo = [result stringForColumn:@"to2"];
        
        self.order2.strLogs = [result stringForColumn:@"logs"];
        
        self.order2.strPhoto = [result stringForColumn:@"photo"];
        
        //NSLog ( @" strCompan = %@, strOrderNo = %@, photo = %@", self.order2.strCompany, self.order2.strOrderNo, self.order2.strPhoto);
    }
}

//创建数据表
-(void )createTable
{
    //创建表添加字段SQL字符串
    NSString *createTableString = @"create table if not exists order2(serial integer primary key autoincrement, orderno varchar(32), company varchar(32), status varchar(32), updatetime varchar(32), remark varchar(32), goods varchar(32), from2 varchar(32), to2 varchar(32), logs varchar(32), photo varchar(32))" ;
    
    //创建表
    BOOL bCreateTableString = [self.dataBase executeUpdate:createTableString];

    //NSLog(@"数据表是否存在，创建表结果CreateTableString = %d ", bCreateTableString );
}

//插入数据
-( void )tableInsert
{
    //插入一条数据
    NSString *sql = @"insert into order2(company) values(?)";
    
    BOOL bInsert = [self.dataBase executeUpdate :sql, @"仙海"];

    //NSLog ( @"插入一条记录,bInsert = :%d" ,bInsert);
}

@end
